/**
 * 
 */
package com.base.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;



/**
 * @author ricky
 *
 */
public class MainObjectServer {
	/**
     * 服务端监听的端口地址
     */
    private static final int portNumber = 7878;
	public static void main(String[] args) {
		 EventLoopGroup bossGroup = new NioEventLoopGroup();
	     EventLoopGroup workerGroup = new NioEventLoopGroup();
	        try {
	            ServerBootstrap b = new ServerBootstrap();
	            b.group(bossGroup, workerGroup);
	            b.channel(NioServerSocketChannel.class);
	            b.childHandler(new ChannelInitializer<SocketChannel>(){

					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ChannelPipeline pipeline = ch.pipeline();
						pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers.cacheDisabled(this
				                .getClass().getClassLoader())));
						pipeline.addLast("encoder", new ObjectEncoder());
						pipeline.addLast("handler", new ObjectServerHandler());
						
					}
	            	
	            }).childOption(ChannelOption.SO_KEEPALIVE , true );

	            // 服务器绑定端口监听
	            ChannelFuture f = b.bind(portNumber).sync();
	            // 监听服务器关闭监听
	            f.channel().closeFuture().sync();

	            // 可以简写为
	            /* b.bind(portNumber).sync().channel().closeFuture().sync(); */
	        }
	        catch (InterruptedException e) {
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
   }

	
}
